/*
 * @Author: Jiraiya
 * @Date: 2020-03-16 16:32:19
 * @LastEditors: Jiraiya
 * @LastEditTime: 2020-03-16 17:18:09
 * @Description: 
 */

 
/**
 * 1.初始的时候整个宏任务队列只有一个script任务
 * 2.宏任务执行过程中遇到微任务直接加入微任务队列
 * 3.一个宏任务执行完，查看微任务队列有任务，把所有微任务清理掉
 * 4.GUI(图形用户界面)渲染
 * 5.继续执行宏任务队列第二个任务，依次循环
 * 宏任务：setTimeout,setInterval,I/O,UI交互事件，postMessage,MessageChannel,setImmediate
 * 微任务：Promise.then,MutationObserver,process.nextTick
 * window.requestAnimationFrame()要求浏览器在下次重绘之前调用指定的回调函数更新动画
 */

//🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏
console.log(1);
setTimeout(function() {
    console.log(2);
}, 0);
new Promise(function(resolve) {
    console.log(3);
    resolve(Date.now());
}).then(function() {
    console.log(4);
});
console.log(5);
setTimeout(function() {
    new Promise(function(resolve) {
        console.log(6);
        resolve(Date.now());
    }).then(function() {
        console.log(7);
    });
}, 0); // 1 3 5 4 2 6 7
/**
 * 1.拿出第一个宏任务执行console.log(1)  1
 * 2.将 console.log(2)加入宏任务队列
 * 3.执行console.log(3) 3 并将console.log(4)加入微任务队列
 * 4.执行console.log(5) 5
 * 5.将console.log(6) console.log(7)加入宏任务队列
 * 6.执行微任务队列 4
 * 7.再取一个宏任务执行 2
 * 8.再取一个宏任务执行 6
 * 9.加入微任务console.log(7)
 * 10.执行微任务 7
 */



//🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏
console.log(1);
var start = Date.now();
setTimeout(function() {
    console.log(2);
}, 0);
setTimeout(function() {
    console.log(4, Date.now() - start);
}, 400);
Promise.resolve().then(function() {
    var sum = function(a, b) {
        return Number(a) + Number(b);
    }
    var res = [];
    for(var i=0; i<5000000; i++) {
        var a = Math.floor(Math.random()*100);
        var b = Math.floor(Math.random()*200);
        res.push(sum(a, b));
    }
    res = res.sort();
    console.log(3);
})// 1 3 2 4

//🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏
function A() {
    return Promise.resolve(Date.now());
}
async function B() {
    console.log(Math.random());
    let now = await A();
    console.log(now);
}
console.log(1);
B();
console.log(2);
// 1 随机数 2 时间


//等同于
function B() {
    console.log(Math.random());
    A().then(function(now) {
        console.log(now);
    })
}
console.log(1);
B();
console.log(2);